import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Alert,
  Dimensions,
  Animated,
} from 'react-native';
import {
  Camera,
  useCameraDevices,
  useCameraPermission,
  ReadonlyFrameProcessor,
  PhotoFile,
} from 'react-native-vision-camera';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Icon from '../components/Icon';
import {
  PinchGestureHandler,
  PinchGestureHandlerGestureEvent,
  State,
} from 'react-native-gesture-handler';

interface CameraViewProps {
  showHdrButton?: boolean; // 控制HDR按钮显示，默认隐藏
  showGridButton?: boolean; // 控制网格按钮显示，默认隐藏
  showFlashButton?: boolean; // 控制闪光灯按钮显示，默认显示
  showFrameOverlay?: boolean; // 控制拍照区域线框显示，默认显示
  showFrontRearButton?: boolean;
  frameProcessor?: ReadonlyFrameProcessor;
  onPhotoCaptured?: (photoUri: PhotoFile) => void; // 拍照完成回调
}

const CameraView: React.FC<CameraViewProps> = ({
  showHdrButton = false,
  showGridButton = false,
  showFlashButton = true,
  showFrameOverlay = false,
  showFrontRearButton = true,
  frameProcessor,
  onPhotoCaptured,
}) => {
  const [isCameraFront, setIsCameraFront] = useState(false);
  const [isFlashOn, setIsFlashOn] = useState(false);
  const [isHdrMode, setIsHdrMode] = useState(false);
  const [showGrid, setShowGrid] = useState(false);
  const [zoom, setZoom] = useState(1);
  const [showZoomIndicator, setShowZoomIndicator] = useState(false);
  const [zoomValue, setZoomValue] = useState(1);
  const cameraRef = useRef<Camera>(null);
  const insets = useSafeAreaInsets();
  const pinchRef = useRef(null);

  // 用于拍照动画的透明度
  const fadeAnim = useRef(new Animated.Value(0)).current;

  // 获取相机权限状态和请求权限的方法
  const { hasPermission, requestPermission } = useCameraPermission();

  // 请求相机权限
  useEffect(() => {
    if (!hasPermission) {
      requestPermission();
    }
  }, [hasPermission]);

  const devices = useCameraDevices();
  const device = isCameraFront
    ? devices.find(d => d.position === 'front')
    : devices.find(d => d.position === 'back');

  // 如果没有权限，显示权限请求界面
  if (!hasPermission) {
    return (
      <View style={styles.permissionContainer}>
        <TouchableOpacity onPress={requestPermission}>
          <Icon name="photo-camera" size={60} color="white" />
        </TouchableOpacity>
      </View>
    );
  }

  if (!device) {
    return <Text>没有找到相机设备！</Text>;
  }

  const toggleCameraType = () => {
    setIsCameraFront(!isCameraFront);
  };

  const toggleFlash = () => {
    setIsFlashOn(!isFlashOn);
  };

  const toggleHdrMode = () => {
    setIsHdrMode(!isHdrMode);
  };

  const toggleGrid = () => {
    setShowGrid(!showGrid);
  };

  // 拍照动画
  const triggerCaptureAnimation = () => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 100,
      useNativeDriver: true,
    }).start(() => {
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 300,
        useNativeDriver: true,
      }).start();
    });
  };

  const takePicture = async () => {
    if (cameraRef.current) {
      try {
        // 触发动画
        triggerCaptureAnimation();

        const photo = await cameraRef.current.takePhoto({
          flash: isFlashOn ? 'on' : 'off',
        });
        // 如果提供了回调函数，则调用它
        if (onPhotoCaptured) {
          onPhotoCaptured(photo);
        }
      } catch (error) {
        Alert.alert('Error', 'Failed to capture photo.');
      }
    }
  };

  // 处理双指缩放手势
  const onPinchGestureEvent = (event: PinchGestureHandlerGestureEvent) => {
    const { scale } = event.nativeEvent;
    const newZoom = Math.max(1, Math.min(scale * zoom, 10)); // 限制缩放范围在1-10倍
    setZoomValue(newZoom);
  };

  const onPinchHandlerStateChange = (
    event: PinchGestureHandlerGestureEvent,
  ) => {
    if (event.nativeEvent.state === State.END) {
      setZoom(zoomValue);
      setShowZoomIndicator(false);
    } else if (event.nativeEvent.state === State.BEGAN) {
      setShowZoomIndicator(true);
    }
  };

  // 渲染网格线
  const renderGrid = () => {
    if (!showGrid) return null;

    return (
      <View style={styles.gridContainer}>
        <View style={styles.gridLineHorizontal} />
        <View style={[styles.gridLineHorizontal, { top: '66.66%' }]} />
        <View style={styles.gridLineVertical} />
        <View style={[styles.gridLineVertical, { left: '66.66%' }]} />
      </View>
    );
  };

  // 渲染拍照区域线框
  const renderFrameOverlay = () => {
    if (!showFrameOverlay) return null;

    return (
      <View style={styles.frameOverlayContainer}>
        {/* 四个角的标记 - 增加线长和粗度 */}
        {/* 左上角 */}
        <View style={[styles.frameCorner, styles.frameCornerTopLeft]} />
        <View style={[styles.frameCorner, styles.frameCornerTopRight]} />
        <View style={[styles.frameCorner, styles.frameCornerBottomLeft]} />
        <View style={[styles.frameCorner, styles.frameCornerBottomRight]} />
      </View>
    );
  };

  // 渲染缩放指示器
  const renderZoomIndicator = () => {
    if (!showZoomIndicator) return null;

    return (
      <View style={styles.zoomIndicator}>
        <Text style={styles.zoomIndicatorText}>{zoomValue.toFixed(1)}x</Text>
      </View>
    );
  };

  return (
    <View style={styles.container}>
      <PinchGestureHandler
        onGestureEvent={onPinchGestureEvent}
        onHandlerStateChange={onPinchHandlerStateChange}
        ref={pinchRef}
      >
        <View style={StyleSheet.absoluteFill}>
          <Camera
            ref={cameraRef}
            style={styles.camera}
            device={device}
            isActive={true}
            photo={true}
            video={false}
            zoom={zoom}
            frameProcessor={frameProcessor}
          />
        </View>
      </PinchGestureHandler>

      {renderGrid()}
      {renderFrameOverlay()}
      {renderZoomIndicator()}

      {/* 拍照动画效果 */}
      <Animated.View
        style={[
          styles.captureAnimation,
          {
            opacity: fadeAnim,
          },
        ]}
      />

      {/* 顶部控制栏 */}
      <View style={[styles.topControls, { paddingTop: insets.top }]}>
        {showFlashButton && (
          <TouchableOpacity style={styles.controlButton} onPress={toggleFlash}>
            <Icon
              name={isFlashOn ? 'flash-on' : 'flash-off'}
              size={24}
              color="white"
            />
          </TouchableOpacity>
        )}

        {showHdrButton && (
          <TouchableOpacity
            style={styles.controlButton}
            onPress={toggleHdrMode}
          >
            <Icon
              name={isHdrMode ? 'hdr-on' : 'hdr-off'}
              size={24}
              color="white"
            />
          </TouchableOpacity>
        )}

        {showGridButton && (
          <TouchableOpacity style={styles.controlButton} onPress={toggleGrid}>
            <Icon
              name={showGrid ? 'grid-on' : 'grid-off'}
              size={24}
              color="white"
            />
          </TouchableOpacity>
        )}

        {showFrontRearButton && (
          <TouchableOpacity
            style={styles.controlButton}
            onPress={toggleCameraType}
          >
            <Icon
              name={isCameraFront ? 'camera-front' : 'camera-rear'}
              size={24}
              color="white"
            />
          </TouchableOpacity>
        )}
      </View>

      {/* 底部控制栏 */}
      <View style={[styles.bottomControls, { paddingBottom: insets.bottom }]}>
        <TouchableOpacity style={styles.captureButton} onPress={takePicture}>
          <View style={styles.captureButtonInner} />
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'black',
  },
  camera: {
    flex: 1,
  },
  captureAnimation: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'white',
  },
  gridContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.2)',
  },
  gridLineHorizontal: {
    position: 'absolute',
    left: 0,
    right: 0,
    height: 1,
    backgroundColor: 'rgba(255,255,255,0.2)',
    top: '33.33%',
  },
  gridLineVertical: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    width: 1,
    backgroundColor: 'rgba(255,255,255,0.2)',
    left: '33.33%',
  },
  frameOverlayContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  frameLine: {
    position: 'absolute',
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
  },
  frameLineHorizontal: {
    left: '10%',
    right: '10%',
    height: 1,
  },
  frameLineVertical: {
    top: '20%',
    bottom: '20%',
    width: 1,
  },
  frameCorner: {
    position: 'absolute',
    width: 20, // 缩短长度
    height: 20, // 缩短长度
    borderColor: 'white',
  },
  frameCornerTopLeft: {
    top: '20%',
    left: '10%',
    borderTopWidth: 2,
    borderLeftWidth: 2,
  },
  frameCornerTopRight: {
    top: '20%',
    right: '10%',
    borderTopWidth: 2,
    borderRightWidth: 2,
  },
  frameCornerBottomLeft: {
    bottom: '20%',
    left: '10%',
    borderBottomWidth: 2,
    borderLeftWidth: 2,
  },
  frameCornerBottomRight: {
    bottom: '20%',
    right: '10%',
    borderBottomWidth: 2,
    borderRightWidth: 2,
  },
  topControls: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 20,
    backgroundColor: 'rgba(0,0,0,0.3)',
  },
  bottomControls: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: 'rgba(0,0,0,0.3)',
    gap: 40,
  },
  controlButton: {
    backgroundColor: 'rgba(255,255,255,0.2)',
    borderRadius: 20,
    padding: 8,
    marginHorizontal: 5,
  },
  controlButtonText: {
    color: 'white',
    fontSize: 14,
  },
  captureButton: {
    width: 70,
    height: 70,
    borderRadius: 35,
    borderWidth: 3,
    borderColor: 'white',
    backgroundColor: 'transparent',
    justifyContent: 'center',
    alignItems: 'center',
  },
  captureButtonInner: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: 'white',
  },
  recordingIndicator: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'red',
  },
  // 权限相关样式
  permissionContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'black',
  },
  permissionButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  // 缩放指示器样式
  zoomIndicator: {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: [{ translateX: -50 }, { translateY: -50 }],
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    borderRadius: 20,
    paddingVertical: 10,
    paddingHorizontal: 20,
  },
  zoomIndicatorText: {
    color: 'white',
    fontSize: 24,
    fontWeight: 'bold',
  },
});

export default CameraView;
